#include "ResSound.h"

ResSound::ResSound(std::string filename, char flags, sf::Vector2i position, float volume, float pitch)
    : soundFlags(flags)
    , volumeMax(volume)
    , position(position)
    , todoPlay(false)
    , todoStop(false)
    , todoPause(false)
    , fileName(filename)
{    
    soundBuffer.LoadFromFile(filename);
    SetBuffer(soundBuffer);
    (soundFlags & SOUND_REPEAT) ? SetLoop(true) : SetLoop(false);
    SetPitch(pitch);
    SetVolume(volume);
}

float ResSound::getVolumeMax() const
{
    return volumeMax;
}

void ResSound::setVolumeMax( float volumeMax )
{
    volumeMax = volumeMax;
}

void ResSound::smoothPause( float duration )
{
    todoPlay = false;
    todoStop = false;
    todoPause = true;
    smoothTimeRemaining = duration;
    smoothTime = duration;
}

void ResSound::instantPause()
{
    Pause();
}

void ResSound::update( float delta )
{
    if (todoPause || todoStop)
    {
        if (GetVolume() > 0)
        {
            float tmpMinus = volumeMax*(delta / smoothTime);
            (tmpMinus < GetVolume()) ? SetVolume(GetVolume() - tmpMinus) : SetVolume(0.0f);
        }
        smoothTimeRemaining -= delta;
        if (GetVolume() == 0.0f)
        {
            smoothTimeRemaining = 0.0f;
            if (todoPause)
            {Pause(); todoPause = false;}
            else if(todoStop)
            {Stop(); todoStop = false;}
        }
    }
    else if (todoPlay)
    {
        if (GetStatus() != sf::SoundSource::Playing)
        {Play();}
        if (GetVolume() < volumeMax)
        {
            float tmpPlus = volumeMax*(delta / smoothTime);
            if(tmpPlus + GetVolume() < volumeMax) 
            {SetVolume(GetVolume() + tmpPlus);}
            else
            {SetVolume(volumeMax); todoPlay = false; smoothTimeRemaining = 0.0f;}
        }
    }
}

void ResSound::instantStop()
{
    Stop();
}

void ResSound::smoothStop( float duration )
{
    todoPause = false;
    todoPlay = false;
    todoStop = true;
    smoothTimeRemaining = duration;
    smoothTime = duration;
}

void ResSound::smoothPlay( float duration )
{
    todoPlay = true;
    todoStop = false;
    todoPause = false;
    smoothTimeRemaining = duration;
    smoothTime = duration;
}

void ResSound::instantPlay()
{

}

std::string ResSound::getFileName() const
{
    return fileName;
}

char ResSound::getFlags() const
{
    return soundFlags;
}

sf::Vector2i ResSound::getPosition() const
{
    return position;
}

void ResSound::setPosition( sf::Vector2i position )
{
    position = position;
}
